package pro.shushi.pamirs.hr.core.service;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import pro.shushi.pamirs.core.common.FetchUtil;
import pro.shushi.pamirs.framework.connectors.data.tx.transaction.Tx;
import pro.shushi.pamirs.hr.api.enums.HrSimpleExpEnum;
import pro.shushi.pamirs.hr.api.model.org.Employee;
import pro.shushi.pamirs.hr.api.service.EmployeeService;
import pro.shushi.pamirs.hr.api.tmodel.EmployeeBatchReq;
import pro.shushi.pamirs.meta.annotation.Fun;
import pro.shushi.pamirs.meta.annotation.Function;
import pro.shushi.pamirs.meta.api.dto.config.TxConfig;
import pro.shushi.pamirs.meta.common.exception.PamirsException;
import pro.shushi.pamirs.meta.common.util.ListUtils;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Service
@Fun(EmployeeService.FUN_NAMESPACE)
public class EmployeeServiceImpl implements EmployeeService {

    @Override
    @Function
    public void batchUpdateEmpLabel(EmployeeBatchReq data) {
        if (data.getLabels() == null || data.getLabels().size() == 0) {
            return;
        }
        if (data.getEmployees() == null || data.getEmployees().size() == 0) {
            throw PamirsException.construct(HrSimpleExpEnum.EMPLOYEE_BATCH_UPDATE_EMPLIST_IS_NULL).errThrow();
        }

        List<Long> ids = ListUtils.transform(data.getEmployees(), Employee::getId);
        List<Employee> employeeList = FetchUtil.fetchListByIds(Employee.class, ids);
        for (Employee employee : employeeList) {
            if (CollectionUtils.isEmpty(employee.getLabels())) {
                employee.setLabels(getUniqueLabels(data.getLabels()));
            } else {
                List<String> empLabels = employee.getLabels();
                empLabels.addAll(data.getLabels());
                employee.setLabels(getUniqueLabels(empLabels));
            }
        }

        Tx.build(new TxConfig()).executeWithoutResult(status -> {
            new Employee().updateBatch(employeeList);
        });
    }

    // 使用 LinkedHashSet 去重并保持插入顺序
    private List<String> getUniqueLabels(List<String> labels) {
        Set<String> uniqueLabels = new LinkedHashSet<>(labels);
        return new ArrayList<>(uniqueLabels);
    }

}
